<template>
	<div class="webChat">
		<el-form >
			<el-form-item label="发送用户:" size="small">
				<el-input v-model="username"></el-input>
			</el-form-item>
			<el-form-item size="small">
				<el-button @click="conn()">连接服务器</el-button>
			</el-form-item>
			<el-form-item label="目标用户:" size="small">
				<el-input v-model="toUsername"></el-input>
			</el-form-item>
			<el-form-item label="消息内容:" size="small">
				<el-input v-model="message" type="textarea" rows="10"></el-input>
			</el-form-item>
			<el-from-item>
				<el-button @click="send()">发送消息</el-button>
			</el-from-item>
		</el-form>
	</div>
</template>

<script>
	export default {

		name: 'webChat',
		data() {
			return {
				username: '',
				webSocket: {},
				toUsername: '',
				message: '',
			}
		},
		methods: {
			conn() {
				this.initWebSocket();
			},
			initWebSocket: function() {

				if ('WebSocket' in window) {
					this.webSocket = new WebSocket("ws://localhost:8080/webserver/" + this.username);
					// 连接成功后的回调
					this.webSocket.onopen = e => {
						console.log("成功连接");
					}
					// 接收服务器的消息
					this.webSocket.onmessage = e => {
						var obj = JSON.parse(e.data);
						// messageType 1代表上线、2代表下线、3代表在线名单、4代表普通消息

						if (obj.messageType == 1) {
							console.log(`${obj.username} 用户已上线`);
							this.$message.success(`${obj.username} 用户已上线`);
						}
						if (obj.messageType == 2) {
							console.log(`${obj.username} 用户已下线`);
							this.$message.info(`${obj.username} 用户已下线`);
						}
						if (obj.messageType == 3) {
							this.onLineUsers = obj.onlineUsers;
							this.$message.info(`当前在线用户： ${obj.onlineUsers}`);
						}
						if (obj.messageType == 4) {
							this.$message.success(`${obj.fromUsername} 向您发送了一条消息：${obj.textMessage}`);
						}
					}
					this.webSocket.onclose = e => {
						this.$message.info("你关闭了连接");
						console.log(e.data);
					}
					this.webSocket.onerror = e => {
						this.$message.error("系统异常");
						console.log(e.data);
					}
				} else {
					console.log("当前浏览器不支持");
				}
			},
			closeWebSocket() {
				this.webSocket.close();
			},
			send() {
				let message = {
					message: this.message,
					username: this.username,
					to: this.toUsername,
				}
				this.webSocket.send(JSON.stringify(message));
			}
		},
		created() {

		}
	}
</script>

<style>
	.webChat {
		width: 500px;
		height: 500px;
		box-shadow:0 0 10px gray; 
		padding: 20px;
	}
</style>
